import React, { useEffect, useState } from 'react';
import { setCurrentLanguage } from '@/store/modules/languageSlice';
import { DownOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Dropdown, Space } from 'antd';
import { useTranslation } from 'react-i18next';
import { useDispatch, useSelector } from 'react-redux';
const LanguageIndex: React.FC = () => {

  const { i18n } = useTranslation()
  const [lang,setLang] = useState('zh')
  const dispatch = useDispatch()
  // 从RTK中获取语言状态
  const {currentLanguage} = useSelector(state=>state.languageSlice)
  
  // 初始化当前语言
  const initLanguage = ()=>{
    i18n.changeLanguage(currentLanguage)
  }

  useEffect(()=>{
    initLanguage()
  },[currentLanguage]) // 需要监听语言的变化

  const items: MenuProps['items'] = [
    {
      label: (
        <a href="#" onClick={()=>changeLanguageHandle('zh')}>
          中文
        </a>
      ),
      key: '0',
    },
    {
      label: (
        <a href="#" onClick={()=>changeLanguageHandle('en')}>
          English
        </a>
      ),
      key: '1',
    }
  ];

  

  // 修改当前的语言
  const changeLanguageHandle = (lang: string) => {
    //使用RTK存储当前的语言
    dispatch(setCurrentLanguage(lang))

    // console.log('当前的语言 ',i18n.language)
    // console.log('RTK中语言 ',currentLanguage)
    // 修改当前的语言
    i18n.changeLanguage(currentLanguage)
    setLang(lang)  // 存储语言状态
    // 问题是: 当刷新浏览器,无法保持语言的持久化???? 使用redux存储
  }


  return (
    <div style={{float:"left"}}>
      <Dropdown menu={{ items }} trigger={['click']}>
        <a onClick={(e) => {
          e.preventDefault()
        }}>
          <Space>
            {currentLanguage === 'zh' ? '中文' : 'English'}
            <DownOutlined />
          </Space>
        </a>
      </Dropdown>
    </div>
  )
}

export default LanguageIndex;